package com.runfast.waimai.utils.OAuth2;

import com.runfast.common.Constants;
import com.runfast.waimai.dao.model.*;
import com.runfast.waimai.service.ShiroService;
import com.runfast.waimai.service.WaiMaiRunfastAgentbusinessService;
import com.runfast.waimai.utils.ComUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import java.util.ArrayList;
import java.util.List;


public class ServerRealm extends AuthorizingRealm {
    @Autowired
    private ShiroService shiroService;
    @Autowired
    private WaiMaiRunfastAgentbusinessService waiMaiRunfastAgentbusinessService;
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
       String username = (String) principals.getPrimaryPrincipal();

        //AccountExample accountExample = new AccountExample();
        //accountExample.createCriteria().andUsernameEqualTo(username);
        //List<Account> accounts = accountService.selectByExample(accountExample);


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setStringPermissions(null);

        return authorizationInfo;
    }
    /*** 认证(登录时调用)*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();
       /** 根据accessToken，查询用户信息*/
        SysUserToken tokenEntity = shiroService.queryByToken(accessToken);
       /**token失效*/
        if(tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()){
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }
        SimpleAuthenticationInfo info =null;
        if(tokenEntity != null ){
            if(tokenEntity.getUserType()==1){
                BaseUser baseUser=new BaseUser();
                try {
                    baseUser = shiroService.queryUser(tokenEntity.getUserId().intValue());
                } catch (Exception e) {
                    throw new AuthenticationException(e.getMessage(), e);
                }
                baseUser.setType(1);
                /**
                 * 封装用户参数
                 * */
                List<Integer> alist=new ArrayList<Integer>();
                if(!ComUtil.isEmpty(baseUser.getAgentids())){
                    String[] strIds = baseUser.getAgentids().split(",");
                    for(String strId:strIds){
                        if(!ComUtil.isEmpty(strId)){
                            int rid = ComUtil.getInt(strId);
                            if(rid>0){
                                List<Integer> agentIds=waiMaiRunfastAgentbusinessService.findByAgentId(rid);
                                if(agentIds!=null&&agentIds.size()>0){
                                    alist.addAll(agentIds);
                                }
                            }
                        }
                    }
                }
                baseUser.setAgents(alist);
                RequestContextHolder.currentRequestAttributes().setAttribute(Constants.ADMIN,baseUser,RequestAttributes.SCOPE_SESSION);
                info = new SimpleAuthenticationInfo(baseUser, accessToken, getName());
            }else if(tokenEntity.getUserType()==2){
                WaiMaiRunfastAgentaccounts runfastAgentaccounts=new WaiMaiRunfastAgentaccounts();
                try {
                    runfastAgentaccounts=shiroService.queryAccounts(tokenEntity.getUserId().intValue());
                } catch (Exception e) {
                    throw new AuthenticationException(e.getMessage(), e);
                }
                BaseUser baseUser=new BaseUser();
                baseUser.setId(runfastAgentaccounts.getId());
                baseUser.setUsername(runfastAgentaccounts.getAccounts());
                baseUser.setRealname(runfastAgentaccounts.getName());
                baseUser.setType(2);
               if(runfastAgentaccounts !=null) {
                    WaiMaiRunfastAgentbusiness agentBusiness = waiMaiRunfastAgentbusinessService.selectByPrimaryKey(runfastAgentaccounts.getAgentid());
                    if (agentBusiness != null) {
                        List<Integer> agentIds = waiMaiRunfastAgentbusinessService.findByAgentId(agentBusiness.getId());
                        runfastAgentaccounts.setAgents(agentIds);
                        agentBusiness.setAgents(agentIds);
                    }
                }
                RequestContextHolder.currentRequestAttributes().setAttribute(Constants.CURRENT_RUNFAST_AGENT_ACCOUNTS, runfastAgentaccounts, RequestAttributes.SCOPE_SESSION);
                RequestContextHolder.currentRequestAttributes().setAttribute(Constants.ADMIN,baseUser,RequestAttributes.SCOPE_SESSION);
                info = new SimpleAuthenticationInfo(runfastAgentaccounts, accessToken, getName());
            }else if(tokenEntity.getUserType()==3){
                RunfastBusinessAccounts businessAccounts=null;
                try {
                    businessAccounts=shiroService.queryBusinessAccounts(tokenEntity.getUserId().intValue());
                } catch (Exception e) {
                    throw new AuthenticationException(e.getMessage(), e);
                }
                BaseUser baseUser=new BaseUser();
                baseUser.setId(businessAccounts.getId());
                baseUser.setUsername(businessAccounts.getAccounts());
                baseUser.setRealname(businessAccounts.getName());
                baseUser.setType(3);
                RequestContextHolder.currentRequestAttributes().setAttribute(Constants.CURRENT_RUNFAST_BUSINESS_ACCOUNTS, businessAccounts, RequestAttributes.SCOPE_SESSION);
                RequestContextHolder.currentRequestAttributes().setAttribute(Constants.ADMIN,baseUser,RequestAttributes.SCOPE_SESSION);
                info = new SimpleAuthenticationInfo(businessAccounts, accessToken, getName());
            }
        }
        return info;
    }
}
